/**
 * 格式化创作面板 - 集成格式要求和Word导出
 */

import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  Switch, 
  Space, 
  Alert, 
  Divider,
  Typography,
  Spin,
  message
} from 'antd';
import { 
  FileWordOutlined, 
  SettingOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import DocumentExporter from '../../common/DocumentExporter';
import { aiGenerationService } from '../../../services/ai-generation.service';
import { getFormatPromptByType } from '../../../utils/format-prompt-generator';
import './style.css';

const { Title, Text, Paragraph } = Typography;

interface FormattedCreationPanelProps {
  hotItemId: string;
  platform: string;
  writingAngle: string;
  userPrompt: string;
  modelName: string;
  onContentGenerated?: (content: string, isFormatted: boolean) => void;
}

const FormattedCreationPanel: React.FC<FormattedCreationPanelProps> = ({
  hotItemId,
  platform,
  writingAngle,
  userPrompt,
  modelName,
  onContentGenerated
}) => {
  const [enableFormat, setEnableFormat] = useState(true);
  const [generating, setGenerating] = useState(false);
  const [generatedContent, setGeneratedContent] = useState('');
  const [formatValidation, setFormatValidation] = useState<{
    isValid: boolean;
    issues: string[];
  } | null>(null);

  // 生成内容
  const handleGenerate = async () => {
    if (!userPrompt.trim()) {
      message.warning('请输入创作要求');
      return;
    }

    setGenerating(true);
    try {
      const response = await aiGenerationService.generateHotContentWithFormat(
        hotItemId,
        platform,
        writingAngle,
        userPrompt,
        modelName,
        enableFormat
      );

      if (response.error) {
        message.error(response.error);
        return;
      }

      setGeneratedContent(response.content);
      setFormatValidation(response.formatValidation || null);
      
      // 通知父组件
      onContentGenerated?.(response.content, enableFormat);

      // 显示生成结果信息
      if (enableFormat) {
        if (response.conversionInfo?.conversionApplied) {
          message.info('检测到Markdown格式，已自动转换为HTML格式');
        }
        
        if (response.formatValidation?.isValid) {
          message.success('内容生成成功，格式完全符合要求！');
        } else {
          message.warning('内容已生成，格式已优化但可能需要微调');
        }
      } else {
        message.success('内容生成成功');
      }

    } catch (error) {
      console.error('生成失败:', error);
      message.error('生成失败，请重试');
    } finally {
      setGenerating(false);
    }
  };

  // 获取格式说明
  const getFormatDescription = () => {
    switch (writingAngle) {
      case 'news_report':
      case 'news':
        return '新闻报道格式：标题-导语-正文，倒金字塔结构';
      case 'analysis':
      case 'analysis_report':
        return '分析报告格式：标题-摘要-背景-分析-结论-建议';
      case 'commentary':
      case 'opinion':
        return '评论文章格式：标题-引言-论证-反驳-结论';
      default:
        return '标准格式：一级标题(黑体三号) + 二级标题(黑体四号) + 正文(仿宋小四)';
    }
  };

  return (
    <div className="formatted-creation-panel">
      <Card 
        title={
          <Space>
            <FileWordOutlined />
            <span>格式化创作</span>
          </Space>
        }
        extra={
          <Space>
            <Text>启用格式化</Text>
            <Switch 
              checked={enableFormat}
              onChange={setEnableFormat}
              checkedChildren="开"
              unCheckedChildren="关"
            />
          </Space>
        }
      >
        {/* 格式说明 */}
        {enableFormat && (
          <Alert
            message="格式要求"
            description={
              <div>
                <Paragraph>
                  <strong>当前写作类型：</strong>{getFormatDescription()}
                </Paragraph>
                <Paragraph>
                  <strong>输出格式：</strong>HTML格式，可直接导出为Word文档
                </Paragraph>
                <ul>
                  <li>一级标题：黑体三号(16pt)，段前段后空1行，左对齐</li>
                  <li>二级标题：黑体四号(14pt)，段前段后空0.5行，左对齐</li>
                  <li>正文：仿宋GB-2312小四号(12pt)，两端对齐，首行缩进两个字符</li>
                </ul>
              </div>
            }
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        {/* 生成按钮 */}
        <div className="generation-controls">
          <Button
            type="primary"
            size="large"
            loading={generating}
            onClick={handleGenerate}
            disabled={!userPrompt.trim()}
            block
          >
            {generating ? '正在生成...' : '开始创作'}
          </Button>
        </div>

        {/* 格式验证结果 */}
        {enableFormat && formatValidation && (
          <div className="format-validation" style={{ marginTop: 16 }}>
            <Alert
              message={
                <Space>
                  {formatValidation.isValid ? (
                    <CheckCircleOutlined style={{ color: '#52c41a' }} />
                  ) : (
                    <ExclamationCircleOutlined style={{ color: '#faad14' }} />
                  )}
                  <span>
                    格式验证：{formatValidation.isValid ? '通过' : '需要注意'}
                  </span>
                </Space>
              }
              description={
                !formatValidation.isValid && formatValidation.issues.length > 0 ? (
                  <ul style={{ margin: 0, paddingLeft: 20 }}>
                    {formatValidation.issues.map((issue, index) => (
                      <li key={index}>{issue}</li>
                    ))}
                  </ul>
                ) : null
              }
              type={formatValidation.isValid ? 'success' : 'warning'}
              showIcon={false}
            />
          </div>
        )}

        {/* 内容预览和导出 */}
        {generatedContent && (
          <>
            <Divider />
            <div className="content-actions">
              <Space>
                <Title level={5}>生成结果</Title>
                <DocumentExporter
                  content={generatedContent}
                  title={`${writingAngle}_${new Date().toISOString().split('T')[0]}`}
                />
              </Space>
            </div>
            
            <div className="content-preview">
              {enableFormat ? (
                <div 
                  className="formatted-content"
                  dangerouslySetInnerHTML={{ __html: generatedContent }}
                />
              ) : (
                <div className="plain-content">
                  <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                    {generatedContent}
                  </pre>
                </div>
              )}
            </div>
          </>
        )}
      </Card>
    </div>
  );
};

export default FormattedCreationPanel;
